<?php
//redis 缓存
use Predis\Client;
class redis{
    protected static $redis;
    public static function init(){
        $config = array('host' => '127.0.0.1','port' => 6379);
        try{
            self::$redis = new Client($config);
        }catch(Exception $e){
            \controller::error($e->getMessage());
        }
    }

    public static function set($key,$value,$time=null,$unit='s'){
        self::init();
        if ($time) {
            switch ($unit) {
                case 'h':
                    $time *= 3600;
                    break;
                case 'm':
                    $time *= 60;
                    break;
                case 's':
                case 'ms':
                    break;
                default:
                    \controller::error('单位只能是 h m s ms');
                    break;
            }

                if ($unit=='ms') {
                          self::_psetex($key,$value,$time);
                } else {
                        self::_setex($key,$value,$time);
                }
        }else {
            try{
               self::$redis->set($key,$value);
            }catch(Exception $e){
                \controller::error($e->getMessage());
            }
        }

    }
    public static function get($key) {
        self::init();
        try{
        return self::$redis->get($key);
        }catch(Exception $e){
            \controller::error($e->getMessage());
        }
    }

    public static function delete($key){
        self::init();
            try{
        return self::$redis->del($key);
            }catch(Exception $e){
                \controller::error($e->getMessage());
            }
    }

    private static function _setex($key,$value,$time){
                try{
        self::$redis->setex($key,$time,$value);
                }catch(Exception $e){
                    \controller::error($e->getMessage());
                }
    }

    private static function _psetex($key,$value,$time) {
                    try{
                        self::$redis->psetex($key,$time,$value);
                    }catch(Exception $e){
                        \controller::error($e->getMessage());
                    }
    }
}